package com.google.code.swingonfire.image;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Transparency;

import com.google.code.swingonfire.GraphicsUtils;

public abstract class ComponentBasedImageProvider extends AbstractImageProvider
{

    private final Component component;

    /**
     * Creates an image provider, that gets it's nature from the specified component.
     * 
     * @param component the component
     * @param transparent true if transparent
     */
    public ComponentBasedImageProvider(Component component, boolean transparent)
    {
        this(component, transparent, Double.NaN);
    }

    /**
     * Creates an image provider, that gets it's nature from the specified component.
     * 
     * @param component the component
     * @param transparent true if transparent
     * @param updateAfter a timespan in seconds - the image will be automatically updated, if it hasn't been access for
     *            the specified time. Specify updateAfter <= 0 to update the image each time it is accessed, specify
     *            updateAfter = Double.NaN to disable auto update
     */
    public ComponentBasedImageProvider(Component component, boolean transparent, double updateAfter)
    {
        super(transparent, updateAfter);

        this.component = component;
    }

    /**
     * Returns the component
     * 
     * @return the component
     */
    public Component getComponent()
    {
        return component;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Dimension getPreferredSize()
    {
        return component.getSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Image createImage(int width, int height)
    {
        GraphicsConfiguration graphicsConfiguration = component.getGraphicsConfiguration();

        if (graphicsConfiguration == null)
        {
            return GraphicsUtils.createCompatibleImage(width, height, isTransparent());
        }

        return graphicsConfiguration.createCompatibleImage(width, height, (isTransparent()) ? Transparency.TRANSLUCENT
            : Transparency.OPAQUE);
    }

}
